<template>
  <Layout>
    <div ref="mainContainer" class="main-detail" v-loding="isLoding">
      <BlogDetail :blog="data" v-if="data" />
      <BlogComment v-if="!isLoding" />
    </div>
    <template #right>
      <div class="right-container" v-loding="isLoding">
        <BlogTOC :toc="data.toc" />
      </div>
    </template>
  </Layout>
</template>

<script>
import fetchData from "@/mixins/fatchData"; // 引入公共远程获取数据
import { getBlog } from "@/api/blog"; // 引入详情数据
import BlogDetail from "./components/BlogDetail.vue";
import BlogTOC from "./components/BlogTOC.vue";
import Layout from "@/components/Layout";
import BlogComment from "./components/BlogComment.vue";
export default {
  mixins: [fetchData({})],
  components: {
    BlogDetail,
    BlogTOC,
    Layout,
    BlogComment,
  },
  methods: {
    async fetchData() {
      // 获取数据
      return await getBlog();
    },
    hanleSelect() {
      // 触发事件mainscroll
      // 事件总线
      // mainscroll 事件名  mainContainer 滚动的dom元素
      this.$bus.$emit("mainscroll", this.$refs.mainContainer);
    },
    handleTop(scroll) {
      this.$refs.mainContainer.scrollTop = scroll;
    },
  },
  created() {
    // 监听top组件传递的事件
    this.$bus.$on("setMainScroll", this.handleTop);
  },
  mounted() {
    // 添加滚动事件
    this.$refs.mainContainer.addEventListener("scroll", this.hanleSelect);
  },
  beforeDestroy() {
    this.$bus.$emit("mainscroll");
    // 移除滚动事件
    this.$refs.mainContainer.removeEventListener("scroll", this.hanleSelect);
    this.$bus.$off("mainScrollTop", this.handleTop);
  },
  // 更新DOM完成
  updated() {
    const hash = location.hash; // 保存原有hash值
    location.hash = "";
    setTimeout(() => {
      location.hash = hash;
    }, 500);
  },
};
</script>

<style lang="less" scoped>
.main-detail {
  height: 100%;
  overflow-y: scroll;
  position: relative;
  padding: 20px;
  box-sizing: border-box;
  scroll-behavior: smooth;
}
.right-container {
  width: 300px;
  height: 100%;
  overflow-y: scroll;
  position: relative;
}
</style>